package com.ptsz.mydatbase.location;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import com.ptsz.mydatbase.R;
public class Location extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);


        findViewById(R.id.loc).setOnClickListener(v -> {
            requestLocationPermission();
        });


    }

    private static final int REQUEST_CODE_LOCATION = 100;

    private void requestLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_CODE_LOCATION);
        } else {
            startHighAccuracyLocation();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_LOCATION && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startHighAccuracyLocation();
        }
    }

    private LocationManager locationManager;
    private LocationListener locationListener;

    private void startHighAccuracyLocation() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // 定义定位条件（高精度模式）
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setPowerRequirement(Criteria.POWER_HIGH); // 高功耗模式
        criteria.setAltitudeRequired(true); // 需要海拔数据

        // 获取最佳 Provider
        String provider = locationManager.getBestProvider(criteria, true);

        if (provider == null) {
            Log.e("GPS", "设备不支持高精度定位");
            return;
        }

        // 检查 GPS 是否开启
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            openGpsSettings(); // 引导用户开启 GPS
            return;
        }

        // 注册定位监听
        locationListener = new LocationListener() {

            @Override
            public void onLocationChanged(@NonNull android.location.Location location) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                float accuracy = location.getAccuracy(); // 精度（米）
                Log.d("GPS定位", String.format("纬度: %.6f, 经度: %.6f, 精度: %.1f米", latitude, longitude, accuracy));
                Toast.makeText(Location.this, String.format("纬度: %.6f, 经度: %.6f, 精度: %.1f米", latitude, longitude, accuracy), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };

        // 请求定位更新（最小时间间隔 1 秒，最小距离变化 0 米）
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    1000,       // 最小时间间隔（毫秒）
                    0,          // 最小距离变化（米）
                    locationListener,
                    Looper.getMainLooper()
            );
        }
    }

    // 跳转 GPS 设置
    private void openGpsSettings() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }

    // 停止定位
    private void stopLocationUpdates() {
        if (locationManager != null && locationListener != null) {
            locationManager.removeUpdates(locationListener);
        }
    }

}